package com.cunfang.base.controller;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cunfang.entity.Page;
import com.cunfang.entity.PageData;
import com.cunfang.entity.Tree;
import com.cunfang.entity.UserInfo;
import com.cunfang.util.CONNECTOR;
import com.cunfang.util.RequestResponseContext;
import com.cunfang.util.SysUtil;
import com.cunfang.util.UuidUtil;

/**
 * @功能：业务处理类需要继承的基础类
 * @作者：RC
 * @日期：2016-11-03
 * */
@ResponseBody
public abstract class BaseController {

	/**
	 * 得到PageData
	 */
	public PageData getPageData() throws IOException {
		if ("GET".equals(this.getRequest().getMethod())) {
			return this.getParameter();
		} else {
			return SysUtil.ConvertJSONObjectInfo(this.GetParameter());
		}
	}

	/**
	 * 得到request对象
	 */
	public HttpServletRequest getRequest() {
		// HttpServletRequest request = ((ServletRequestAttributes)
		// RequestContextHolder
		// .getRequestAttributes()).getRequest();
		// return request;
		return RequestResponseContext.getRequest();
	}

	/**
	 * 得到response对象
	 */
	public HttpServletResponse getResponse() {
		return RequestResponseContext.getResponse();
	}

	/**
	 * 
	 * @功能: 得到当前登录人的session
	 * @作者: ZhuHongKai
	 * @日期: 2017年1月13日
	 */
	public UserInfo getUserInfo() {
		UserInfo user = null;
		HttpSession session = this.getRequest().getSession();
		if (session != null) {
			/*user = (UserInfo) session.getAttribute(Const.SESSION_USER);*/
		}
		return user;
	}



	/**
	 * 得到当前token保存的ID
	 * */
	public String GetUserID() {
		String token = this.GetToken();
		return CONNECTOR.GetTokenValue(token);
	}

	/**
	 * 得到当前的token
	 * */
	public String GetToken() {
		/* 第一： token存放在header中 */
		String token = this.getRequest().getHeader("token");
		if (token == null) {
			/* 第二：token存放在url参数中 */
			token = this.getRequest().getParameter("token");
		}
		return token;
	}

	/**
	 * 
	 * @功能: 得到当前接口参数（适用get请求）
	 * @作者: ZhuHongKai
	 * @日期: 2017年2月17日
	 */
	public PageData getParameter() {
		PageData pd = new PageData();
		Map<String, String[]> map = (Map<String, String[]>) this.getRequest()
				.getParameterMap();
		for (String name : map.keySet()) {
			String[] values = map.get(name);
			if (values.length > 0) {
				pd.put(name, values[0]);
			} else {
				pd.put(name, "");
			}
		}
		return pd;
	}

	/**
	 * 得到当前接口的参数(适用于传入的json格式)
	 * */
	public JSONObject GetParameter() throws IOException {
		BufferedReader reader = this.getRequest().getReader();
		String line = "";
		StringBuffer inputString = new StringBuffer();
		while ((line = reader.readLine()) != null) {
			inputString.append(line);
		}
		return JSONObject.fromObject(inputString.toString());
	}

	/**
	 * 得到36位的uuid
	 * 
	 */
	public String getUUID() {
		return UuidUtil.getUUID().toUpperCase();
	}

	/**
	 * @功能：打印List Tree
	 * @作者：RC
	 * @日期：2016-11-05
	 * */
	public void outListTree(List<Tree> list) {
		String str = "";
		if (list.size() > 0) {
			str = JSONArray.fromObject(list).toString();
		} else {
			str = "[]";
		}
		str = "{\"status\":\"0\",\"msg\":\"\",\"data\":" + str + "}";
		outTString(str);
	}

	/**
	 * @功能：打印PageData
	 * @作者：RC
	 * @日期：2016-11-03
	 * */
	@SuppressWarnings("rawtypes")
	public void outPageData(PageData pd, PageData dateFormat) {
		String str = "";
		Map.Entry me;
		str = "{";
		if (pd != null) {
			Iterator it = pd.entrySet().iterator();
			while (it.hasNext()) {
				me = (Map.Entry) it.next();
				str += "\""
						+ me.getKey()
						+ "\":\""
						+ this.scanString(me.getValue(), me.getKey(),
								dateFormat) + "\",";
			}
		}
		if (str.length() > 1) {
			str = str.substring(0, str.length() - 1); /* 去除逗号 */
		}
		str += "}";
		str = "{\"status\":\"0\",\"msg\":\"\",\"data\":" + str + "}";
		outTString(str);
	}

	public void outPageData(PageData pd) {
		outPageData(pd, new PageData());
	}

	public void outPageData(PageData pd, String dateFormat) {
		PageData date = new PageData();
		date.put("ALL", dateFormat);
		outPageData(pd, date);
	}

	/**
	 * @功能：打印List PageData
	 * @作者：RC
	 * @日期：2016-11-04
	 * */
	@SuppressWarnings("rawtypes")
	public void outListPageData(List<PageData> list, PageData dateFormat) {
		String str = "";
		Map hs;
		Iterator it;
		Map.Entry me;
		/* 拼接 json */
		str += "[";
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i) == null)
					continue;

				hs = list.get(i).map;
				str += "{";
				it = hs.entrySet().iterator();
				while (it.hasNext()) {
					me = (Map.Entry) it.next();
					str += "\""
							+ me.getKey()
							+ "\":\""
							+ this.scanString(me.getValue(), me.getKey(),
									dateFormat) + "\",";
				}
				str = str.substring(0, str.length() - 1); /* 去除逗号 */
				str += "},";
			}
			if (list.size() > 0) {/* 去除逗号 */
				str = str.substring(0, str.length() - 1);
			}
		}
		str += "]";
		str = "{\"status\":\"0\",\"msg\":\"\",\"data\":" + str + "}";
		outTString(str);
	}

	public void outListPageData(List<PageData> list) {
		outListPageData(list, new PageData());
	}

	public void outListPageData(List<PageData> list, String dateFormat) {
		PageData date = new PageData();
		date.put("ALL", dateFormat);
		outListPageData(list, date);
	}

	/**
	 * @功能：打印Page
	 * @作者：RC
	 * @日期：2016-11-04
	 * */
	@SuppressWarnings("rawtypes")
	public void outPage(Page page, List<PageData> list, PageData dateFormat) {
		String str = "";
		Map hs;
		Iterator it;
		Map.Entry me;
		/* 拼接 json */
		str += "[";
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i) == null)
					continue;

				hs = list.get(i).map;
				str += "{";
				it = hs.entrySet().iterator();
				while (it.hasNext()) {
					me = (Map.Entry) it.next();
					str += "\""
							+ me.getKey()
							+ "\":\""
							+ this.scanString(me.getValue(), me.getKey(),
									dateFormat) + "\",";
				}
				str = str.substring(0, str.length() - 1); /* 去除逗号 */
				str += "},";
			}
			if (list.size() > 0) {/* 去除逗号 */
				str = str.substring(0, str.length() - 1);
			}
		}
		str += "]";

		/* 拼接分页... */
		str = "{\"totalpage\":" + page.getTotalPage() + ",\"currpage\":"
				+ page.getCurrentPage() + ",\"count\":" + page.getShowCount()
				+ ",\"totalresult\":\"" + page.getTotalResult()
				+ "\",\"data\":" + str + "}";
		str = "{\"status\":\"0\",\"msg\":\"\",\"data\":" + str + "}";
		outTString(str);
	}

	public void outPage(Page page, List<PageData> list) {
		outPage(page, list, new PageData());
	}

	public void outPage(Page page, List<PageData> list, String dateFormat) {
		PageData date = new PageData();
		date.put("ALL", dateFormat);
		outPage(page, list, date);
	}

	/**
	 * @功能：打印错误记录
	 * @作者：RC
	 * @日期：2016-11-03
	 * */
	public void outError(String str) {
		str = "{\"status\":\"1\",\"msg\":\"" + this.scanString(str) + "\"}";
		outTString(str);
	}

	/**
	 * 
	 * @功能: 打印登录失效信息
	 * @作者: ZhuHongKai
	 * @日期: 2017年3月4日
	 */
	public void outLoginError(String str) {
		str = "{\"status\":\"3\",\"msg\":\"" + this.scanString(str) + "\"}";
		outTString(str);
	}

	/**
	 * @功能：打印正确信息
	 * @作者：RC
	 * @日期：2016-11-03
	 * */
	public void outString(String str) {
		str = "{\"status\":\"0\",\"msg\":\"" + this.scanString(str) + "\"}";
		outTString(str);
	}

	/**
	 * @功能：向客户端打印输出数据流
	 * @作者：RC
	 * @日期：2016-11-03
	 * */
	public void outTString(String str) {
		try {
			HttpServletResponse response = this.getResponse();
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			if (str != null) {
				str = str.trim();
			}
			out.write(str);
			if (out != null) {
				out.flush();
				out.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void outByteArray(ServletOutputStream out) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		try {
			output.writeTo(out);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * JSon 数据中的String 传递数据时，需要处理好特殊字符 JSon数据中有特殊字符 1:引号 如果是使用单引号，来括值的话，那String
	 * 中 ' 单引号为特殊字符 2：正斜杠，反斜杠，换行符号等 3:另外，必须用 (") 而非 (') 表示字符串：
	 * 
	 * @param str
	 * @return String类型
	 * @createTime 2014-9-4
	 * @author Sunqinbo
	 */
	public String scanString(Object obj, Object key, PageData pd) {
		if (obj == null) {
			return "";
		}
		/* 转换时间类型 */
		if (obj instanceof java.util.Date && pd != null) {
			SimpleDateFormat formatter = null;
			if (pd.containsKey(key)) {
				formatter = new SimpleDateFormat(pd.getString(key));
			} else {
				formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			}
			return formatter.format(obj);
		}
		String s = obj.toString();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			switch (c) {
			case '\"':
				sb.append("\\\"");
				break;
			case '\\':
				sb.append("\\\\");
				break;
			case '/':
				sb.append("\\/");
				break;
			case '\b':
				sb.append("\\b");
				break;
			case '\f':
				sb.append("\\f");
				break;
			case '\n':
				sb.append("\\n");
				break;
			case '\r':
				sb.append("\\r");
				break;
			case '\t':
				sb.append("\\t");
				break;
			default:
				sb.append(c);
			}
		}
		return sb.toString();
	}

	public String scanString(Object obj) {
		return scanString(obj, "", null);
	}
}
